﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Caching;
using System.Web;

namespace Se.Framework.Common
{
    public class CacheSvc : ICacheSvc
    {

        public void Add<T>(string key, T obj)
        {
            Add<T>(key, obj, 20);
        }

        public void Add<T>(string key, T obj, int minutes)
        {
            if (Get<T>(key) != null)
            {
                HttpRuntime.Cache.Add(GetFullKey<T>(key), obj, null, DateTime.Now.AddMinutes(minutes), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            else
            {
                HttpRuntime.Cache.Insert(GetFullKey<T>(key), obj, null, DateTime.Now.AddMinutes(minutes), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
            }
        }

        public void AddMany<T>(Dictionary<string, object> data)
        {
            AddMany<T>(data, 20);
        }

        public void AddMany<T>(Dictionary<string, object> data, int minutes) 
        {
            foreach (KeyValuePair<string, object> item in data)
            {
                Add<T>(item.Key, (T)item.Value, minutes);
            }
        }

        public T Get<T>(string key)
        {
            object obj = HttpRuntime.Cache.Get(GetFullKey<T>(key));
            return obj == null ? default(T) : (T)obj;
            
        }

        public IDictionary<string,T> GetMany<T>(ref List<string> keys)
        {
            Dictionary<string, T> cacheObjets = new Dictionary<string, T>();
            List<string> keysRemaining = new List<string>();
            T currentObject;

            foreach (string key in keys)
            {
                currentObject = Get<T>(key);
                if (currentObject != null)
                {
                    cacheObjets.Add(key, currentObject);
                }
                else
                {
                    keysRemaining.Add(key);
                }
            }

            keys = keysRemaining;

            return cacheObjets;
        }

        public void Remove<T>(string key)
        {
            HttpRuntime.Cache.Remove(GetFullKey<T>(key));
        }

        public void RemoveMany<T>(List<string> keys)
        {
            foreach (string key in keys)
            {
                Remove<T>(key);
            }
        }

        private string GetFullKey<T>(string key)
        {
            return string.Format("{0}-{1}", typeof(T).Name, key);
        }
    }
}
